//
//  LGHomeHeaderView.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/8/14.
//

#import "LGHomeHeaderView.h"
#import "LGHomeCalenderCell.h"
#define itemHeight  viewPix(58)
#define itemWidth   (Screen_W-viewPix(24))/4.0
@interface LGHomeHeaderView()<UICollectionViewDelegate,UICollectionViewDataSource>
/**   */
@property (nonatomic , strong)UILabel *organTitle;
/**   */
@property (nonatomic , strong)UIImageView *headView;
/**   */
@property (nonatomic , strong)UILabel *nameLabel;
/**   */
@property (nonatomic , strong)UILabel *postLabel;
/**   */
@property (nonatomic , strong)UIButton *infoBtn;
/**   */
@property (nonatomic , strong)UIButton *codeButton;
/**   */
@property (nonatomic , strong)UIButton *searchButton;
/**   */
@property (nonatomic , strong)UIView *itemView;
/**   */
@property (nonatomic , strong)UILabel *scheduleLabel;
/**  添加咨询 -- 已废弃 */
@property (nonatomic , strong)UIButton *addConsultBtn;
/**  全部日程 */
@property (nonatomic , strong)UIButton *fullScheduleBtn;
/**   */
@property (nonatomic , strong)UICollectionView *collectionView;
/**   */
@property (nonatomic , strong)NSMutableArray *buttonArray;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
/**   */
@property (nonatomic , assign)NSInteger index;
@end

@implementation LGHomeHeaderView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.index = -1;
        [self createSubView];
    }
    return self;
}

-(void)setOrganArray:(NSArray *)organArray{
    _organArray = organArray;
    if (organArray.count>1) {
        self.organBtn.hidden = NO;
        for (NSDictionary *tempDic in organArray) {
            if ([LGNSString(tempDic[@"status"]) isEqualToString:@"1"]) {
                self.organTitle.text = LGNSString(tempDic[@"level_name"]);
                [[NSUserDefaults standardUserDefaults] setValue:LGNSString(tempDic[@"level_id"]) forKey:@"level_id"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }
    }else{
        self.organBtn.hidden = YES;
        self.organTitle.text = @"工作台";
    }
    CGFloat textW = [self.organTitle.text textWidthWithFont:LGFontWeight(18, UIFontWeightMedium) maxHeight:MAXFLOAT]+viewPix(5);
    textW = (textW>Screen_W-viewPix(100))?Screen_W-viewPix(100):textW;
    [self.organTitle mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(textW));
    }];
}

-(void)setDoctorDic:(NSDictionary *)doctorDic{
    _doctorDic = doctorDic;
    NSString *roleType = LGNSString(doctorDic[@"role_type_val"]);
    UIImage *placeHolder = ([roleType isEqualToString:@"99"]||[roleType isEqualToString:@"10"] || [roleType isEqualToString:@"11"] || [roleType isEqualToString:@"40"])?defaultDoctorPic:defaultNursePic;
    [self.headView sd_setImageWithURL:[NSURL URLWithString:LGNSString(doctorDic[@"avatar_url"])] placeholderImage:placeHolder];
    NSString *realname = LGNSString(doctorDic[@"realname"]);
    self.nameLabel.text = (realname.length>6)?[NSString stringWithFormat:@"%@...",[realname substringToIndex:5]]:realname;
    self.postLabel.text = LGNSString(doctorDic[@"profess"]);
    //99:队长医生   10:专家医生  11:进修医生  40:康复医生  20:护士  30:个案管理师    100:其他
    CGFloat searchRight = viewPix(45);
    if([roleType isEqualToString:@"99"] || [roleType isEqualToString:@"10"]){
        //队长、专家医生
        self.codeButton.hidden = NO;
        searchRight = -viewPix(10);
        
    }else if ([roleType isEqualToString:@"20"] || [roleType isEqualToString:@"30"]){
        //护士、个案管理师
        self.codeButton.hidden = YES;
        
    }else{
        //进修医生、康复医生、其他
        self.codeButton.hidden = YES;    //队长医生、专家医生可见 -- 护士、个案管理师、进修医生、康复医生不可见
        
    }
    [self.searchButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.codeButton.mas_left).offset(searchRight);

    }];
}

-(void)setItemArray:(NSArray *)itemArray{
    _itemArray = itemArray;
    for (UIView *view in self.buttonArray) {
        [view removeFromSuperview];
    }
    [self.buttonArray removeAllObjects];
    CGFloat topMargin = statusBarHeight+viewPix(115);
    for (NSInteger i=0; i<itemArray.count; i++) {
        NSDictionary *tempDic = itemArray[i];
        UIButton *button = [UIButton buttonWithTitle:LGNSString(tempDic[@"title"]) titleFont:LGFontWeight(15, UIFontWeightMedium) textColor:@"#333333" imageName:@""];
        button.frame = CGRectMake(viewPix(16)+itemWidth*(i%4), topMargin+itemHeight*(i/4), itemWidth-viewPix(8), itemHeight-viewPix(8));
        button.titleLabel.numberOfLines = 2;
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.layer.borderColor = [UIColor colorWithString:@"#BFD4F5"].CGColor;
        button.layer.borderWidth = 1;
        button.cornerRidus = 5;
        button.tag = 1000+i;
        [button.layer addSublayer:[self itemShadowLayer]];
        [button bringSubviewToFront:button.titleLabel];
        [button addTarget:self action:@selector(itemButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        [self.buttonArray addObject:button];
        //小红帽
        NSInteger number = [tempDic[@"num"] integerValue];
        if(number>0){
            UILabel *numberLabel = [UILabel lableWithText:[NSString stringWithFormat:@"%ld",number] colorString:@"#FFFFFF" textFont:LGFontWeight(14, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
            numberLabel.backgroundColor = [UIColor colorWithString:@"#F84D4D"];
            numberLabel.cornerRidus = viewPix(10);
            [self addSubview:numberLabel];
            [self.buttonArray addObject:numberLabel];
            CGFloat width = (number>9)?viewPix(30):viewPix(20);
            [numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(button).offset(-viewPix(6));
                make.right.equalTo(button).offset(viewPix(6));
                make.width.equalTo(@(width));
                make.height.equalTo(@(viewPix(20)));
            }];
        }
        if (i == itemArray.count-1) {
            self.itemView.frame =  CGRectMake(0, viewPix(10)+kMaxY(button.frame), Screen_W, viewPix(120));
        }
    }
}

-(void)setScheduleArray:(NSArray *)scheduleArray{
    _scheduleArray = scheduleArray;
    [self.collectionView reloadData];
}

//查看个人信息
-(void)infoButtonAciton{
    if(self.delegate && [self.delegate respondsToSelector:@selector(checkDoctorInfoAction)]){
        [self.delegate checkDoctorInfoAction];
    }
}

//搜索
-(void)searchButtonAction{
    if(self.delegate && [self.delegate respondsToSelector:@selector(searchPatientAction)]){
        [self.delegate searchPatientAction];
    }
}

//二维码
-(void)codeButtonAction{
    if(self.delegate && [self.delegate respondsToSelector:@selector(checkQRCodeAction)]){
        [self.delegate checkQRCodeAction];
    }
}

//item点击事件
-(void)itemButtonTouched:(UIButton *)sender{
    NSInteger index = sender.tag-1000;
    NSDictionary *tempDic = self.itemArray[index];
    if(self.delegate && [self.delegate respondsToSelector:@selector(itemButtonTouched:)]){
        [self.delegate itemButtonTouched:LGNSString(tempDic[@"code"])];
    }
}

//添加咨询记录
-(void)addConsultBtnAction{
    if(self.delegate && [self.delegate respondsToSelector:@selector(addConsultRecordAction)]){
        [self.delegate addConsultRecordAction];
    }
}

//全部日程
-(void)fullScheduleBtnAction{
    if(self.delegate && [self.delegate respondsToSelector:@selector(itemButtonTouched:)]){
        [self.delegate itemButtonTouched:@"全部日程"];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.scheduleArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LGHomeCalenderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.normalColor = (indexPath.item == 0 || indexPath.item == self.scheduleArray.count-1)?@"#999999":@"#333333";
    cell.dataDic = self.scheduleArray[indexPath.item];
    NSString *today = LGNSString(self.scheduleArray[indexPath.item][@"date"]);
    if(self.index>=0){
        cell.isSelect = (indexPath.item == self.index)?YES:NO;
    }else{
        cell.isSelect = [today isEqualToString:[self.formatter stringFromDate:[NSDate date]]]?YES:NO;
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.index = indexPath.item;
    [self.collectionView reloadData];
    if(self.delegate && [self.delegate respondsToSelector:@selector(checkScheduleData:)]){
        [self.delegate checkScheduleData:LGNSString(self.scheduleArray[indexPath.row][@"date"])];
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.clipsToBounds = YES;
    [self addSubview:self.organTitle];
    [self addSubview:self.organBtn];
    [self addSubview:self.headView];
    [self addSubview:self.nameLabel];
    [self addSubview:self.postLabel];
    [self addSubview:self.infoBtn];
    [self addSubview:self.codeButton];
    [self addSubview:self.searchButton];
    [self addSubview:self.itemView];
    [self addSubview:self.scheduleLabel];
    [self addSubview:self.addConsultBtn];
    [self addSubview:self.fullScheduleBtn];
    [self addSubview:self.collectionView];

    [self.organTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(statusBarHeight);
        make.left.equalTo(self).offset(viewPix(16));
        make.width.equalTo(@(viewPix(60)));
        make.height.equalTo(@(viewPix(30)));
    }];
    
    [self.organBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.organTitle);
        make.right.equalTo(self.organTitle).offset(viewPix(15));
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.headView.mas_centerY).offset(-viewPix(3));
        make.left.equalTo(self.headView.mas_right).offset(viewPix(12));
        make.right.equalTo(self.searchButton.mas_left).offset(-viewPix(5));
    }];
    [self.postLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameLabel.mas_bottom).offset(viewPix(6));
        make.left.right.equalTo(self.nameLabel);
    }];

    [self.infoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.equalTo(self.headView);
        make.right.equalTo(self.nameLabel);
    }];
    
    [self.codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self).offset(-viewPix(10));
        make.centerY.equalTo(self.headView);
        make.width.equalTo(@(viewPix(45)));
        make.height.equalTo(@(viewPix(64)));
    }];
    
    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.codeButton.mas_left).offset(-viewPix(10));
        make.centerY.width.height.equalTo(self.codeButton);
    }];
    
    [self.scheduleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(viewPix(18));
        make.bottom.equalTo(self.collectionView.mas_top).offset(-viewPix(7));
    }];
    [self.addConsultBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scheduleLabel.mas_right).offset(viewPix(10));
        make.centerY.equalTo(self.scheduleLabel);
        make.width.equalTo(@(viewPix(80)));
        make.height.equalTo(@(viewPix(22)));
    }];
    [self.fullScheduleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self).offset(-viewPix(16));
        make.centerY.equalTo(self.addConsultBtn);
        make.width.equalTo(@(viewPix(80)));
        make.height.equalTo(@(viewPix(22)));
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(viewPix(16));
        make.right.equalTo(self).offset(-viewPix(16));
        make.bottom.equalTo(self).offset(-viewPix(10));
        make.height.equalTo(@(viewPix(60)));
    }];
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc]init];
        _formatter.dateFormat = @"yyyy-MM-dd";
    }
    return _formatter;
}

-(NSMutableArray *)buttonArray{
    if(!_buttonArray){
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}

-(UILabel *)organTitle{
    if(!_organTitle){
        _organTitle = [UILabel lableWithText:@"工作台" colorString:@"#282828" textFont:LGFontWeight(18, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _organTitle;
}

-(UIButton *)organBtn{
    if(!_organBtn){
        _organBtn = [UIButton buttonWithImage:@"blackTipDown16" selectImage:@"blackTipDown16"];
        _organBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _organBtn.hidden = YES;
    }
    return _organBtn;
}

-(UIImageView *)headView{
    if(!_headView){
        _headView = [[UIImageView alloc]initWithFrame:CGRectMake(viewPix(18), viewPix(38)+statusBarHeight, viewPix(64), viewPix(64))];
        _headView.backgroundColor = [UIColor colorWithString:@"#90C3FA"];
        _headView.cornerRidus = viewPix(32);
    }
    return _headView;
}

-(UILabel *)nameLabel{
    if(!_nameLabel){
        _nameLabel = [UILabel lableWithText:@"" colorString:@"#333333" textFont:LGFontWeight(18, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _nameLabel;
}

-(UILabel *)postLabel{
    if(!_postLabel){
        _postLabel = [UILabel lableWithText:@"" colorString:@"#666666" textFont:LGFont(15) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _postLabel;
}

-(UIButton *)infoBtn{
    if(!_infoBtn){
        _infoBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_infoBtn addTarget:self action:@selector(infoButtonAciton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _infoBtn;
}

-(UIButton *)searchButton{
    if(!_searchButton){
        _searchButton = [UIButton buttonWithTitle:@"搜索" titleFont:LGFont(13) textColor:@"#666666" imageName:@"首页-搜索"];
        _searchButton.bounds = CGRectMake(0, 0, viewPix(45), viewPix(64));
        [_searchButton addTarget:self action:@selector(searchButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_searchButton setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:5];
    }
    return _searchButton;
}

-(UIButton *)codeButton{
    if(!_codeButton){
        _codeButton = [UIButton buttonWithTitle:@"二维码" titleFont:LGFont(13) textColor:@"#666666" imageName:@"首页-二维码"];
        _codeButton.bounds = CGRectMake(0, 0, viewPix(45), viewPix(64));
        [_codeButton setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:5];
        [_codeButton addTarget:self action:@selector(codeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeButton;
}

-(UIView *)itemView{
    if(!_itemView){
        _itemView = [[UIView alloc]initWithFrame:CGRectMake(0, viewPix(180)+statusBarHeight, Screen_W, viewPix(120))];
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.frame = CGRectMake(0,0,Screen_W,viewPix(120));
        gradientLayer.startPoint = CGPointMake(0.5, 0);
        gradientLayer.endPoint = CGPointMake(0.5, 1);
        gradientLayer.colors = @[(__bridge id)[UIColor colorWithString:@"#FFFFFF" alpha:0.6].CGColor, (__bridge id)[UIColor colorWithString:@"#FFFFFF"].CGColor, (__bridge id)[UIColor colorWithString:@"#FFFFFF"].CGColor];
        gradientLayer.locations = @[@(0), @(0.6f), @(1.0f)];
        [_itemView.layer addSublayer:gradientLayer];
        _itemView.layer.borderColor = [UIColor colorWithString:@"#FFFFFF"].CGColor;
        _itemView.layer.borderWidth = 1;
        _itemView.cornerRidus = 15;
    }
    return _itemView;
}

-(UILabel *)scheduleLabel{
    if(!_scheduleLabel){
        _scheduleLabel = [UILabel lableWithText:@"日程" colorString:@"#333333" textFont:LGFontWeight(20, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    }
    return _scheduleLabel;
}

-(UIButton *)addConsultBtn{
    if(!_addConsultBtn){
        _addConsultBtn = [UIButton buttonWithTitle:@" 咨询记录" titleFont:LGFontWeight(14, UIFontWeightMedium) textColor:@"#2E9AFC" imageName:@"首页-添加"];
        [_addConsultBtn addTarget:self action:@selector(addConsultBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _addConsultBtn.hidden = YES;
    }
    return _addConsultBtn;
}

-(UIButton *)fullScheduleBtn{
    if(!_fullScheduleBtn){
        _fullScheduleBtn = [UIButton buttonWithTitle:@"全部日程" titleFont:LGFont(14) textColor:@"#333333" imageName:@"grayTip12"];
        _fullScheduleBtn.bounds = CGRectMake(0, 0, viewPix(80), viewPix(22));
        _fullScheduleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_fullScheduleBtn setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:5];
        [_fullScheduleBtn addTarget:self action:@selector(fullScheduleBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _fullScheduleBtn;
}


-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake((Screen_W-viewPix(33))/7.0-1, viewPix(60));
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(viewPix(16), 0, Screen_W-viewPix(32), viewPix(60)) collectionViewLayout:layout];
        [_collectionView registerClass:[LGHomeCalenderCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}

-(CAGradientLayer *)itemShadowLayer{
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = CGRectMake(0,0,itemWidth-viewPix(8),itemHeight-viewPix(8));
    layer.startPoint = CGPointMake(0.5, 0);
    layer.endPoint = CGPointMake(0.5, 1);
    layer.colors = @[(__bridge id)[UIColor colorWithString:@"#F9FAFF"].CGColor, (__bridge id)[UIColor colorWithString:@"#F1F5FF"].CGColor];
    layer.locations = @[@(0), @(1.0f)];
    return layer;
}

@end
